package com.lzp.service;

import com.lzp.model.Coffee;
import com.lzp.repository.CoffeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;

/**
 * @description: CoffeeService
 * @author: lzp
 * @createTime: 2021-12-11 13:10
 **/
@Service
@Slf4j
public class CoffeeService {
    @Autowired
    private CoffeeRepository coffeeRepository;

    @Autowired
    private RedisTemplate<String, Coffee> redisTemplate;

    private static final String COFFEE_CACHE = "springbucks-coffee";

    public List<Coffee> findAllCoffee() {
        return coffeeRepository.findAll();
    }

    public Optional<Coffee> findOneCoffee(String name) {
        // 使用hash形式
        HashOperations<String, String, Coffee> hashOperations = redisTemplate.opsForHash();
        if (redisTemplate.hasKey(COFFEE_CACHE) && hashOperations.hasKey(COFFEE_CACHE, name)) {
            log.info("从Redis缓存中获取指定coffee，{}", name);
            return Optional.of(hashOperations.get(COFFEE_CACHE, name));
        }
        // 缓存中没有则查询
        // 创建条件
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name", exact().ignoreCase());
        Optional<Coffee> coffee = coffeeRepository.findOne(Example.of(Coffee.builder().name(name).build(), matcher));
        log.info("Coffee Found: {}", coffee);
        if (coffee.isPresent()) {
            log.info("将查询结果缓存到Redis，{}", name);
            hashOperations.put(COFFEE_CACHE, name, coffee.get());
            redisTemplate.expire(COFFEE_CACHE, 1, TimeUnit.MINUTES);
        }
        return coffee;
    }
}
